

import time
import tkinter as tk
import datetime
from tkinter import ttk

from douyin import start

import threading
import requests
import certifi
# 时间显示
time_text = None
# 时间线程标志
time_start = True
# 当前时间
now = None
# 时间线程
T = None


arr = []
arr_index = 0


########################################################################


def get_time():
    start_time = datetime.datetime.now()
    url = 'https://www.jishirili.com/time.asp'
    response = requests.get(url, verify=certifi.where())
    response.close()
    if response.status_code == 200:
        timestamp_ms = response.json()
        # 将毫秒转换为秒
        timestamp_sec = timestamp_ms / 1000

        # 将时间戳转换为日期时间对象
        datetime_obj = datetime.datetime.fromtimestamp(timestamp_sec)
        end_time = datetime.datetime.now()
        execution_time = (end_time - start_time)

        return execution_time+datetime_obj
    else:
        return None


def start_time_thread():
    global T
    T = threading.Thread(target=start_time_ling, args=())  # 多线程
    T.daemon = True  # 线程守护，即主进程结束后，此线程也结束。否则主进程结束子进程不结束
    T.start()  # 启动


def start_time_ling():
    global time_start
    global time_text
    global now
    time_start = True
    now = get_time()
    while time_start:
        start_time = datetime.datetime.now()
        timer = '{}'.format(now.strftime("%H:%M:%S"))
        time_text.config(text=timer)
        time.sleep(1)
        end_time = datetime.datetime.now()
        execution_time = (end_time - start_time)
        now = execution_time+now
########################################################################


def wait_cahe(obj):
    """
    时间等等待中
    """
    obj['switch'] = True
    if obj['data_delay'] != 0:
        time.sleep(obj['data_delay']*60)
        obj['log_text'] = 'wait'
        obj['log_label'].config(text='wait')
        obj['data_delay'] = 0

    obj['log_text'] = 'start'
    obj['log_label'].config(text='start')
    # 空值抖音循环
    while obj['switch']:
        more_submit_cache(obj)


def more_submit_cache(obj):
    """
    开始任务
    """
    print('开始')
    start(obj)


def start_thread(obj):
    """
    每个脚本启动一个线程，等待开始时间
    """
    obj['threading'] = threading.Thread(target=wait_cahe, args=(obj,))  # 多线程
    obj['threading'].daemon = True  # 线程守护，即主进程结束后，此线程也结束。否则主进程结束子进程不结束
    obj['threading'].start()  # 启动


def create_windows():
    '''初始化窗口'''

    root = tk.Tk()
    root .title("抖音")
    sw = root.winfo_screenwidth()
    # 得到屏幕宽度
    sh = root.winfo_screenheight()

    # 得到屏幕高度
    ww = 1366
    wh = 768

    x = (sw - ww) / 2
    y = (sh - wh) / 2
    root.geometry("%dx%d+%d+%d" % (ww, wh, x, y))
    root .resizable(width=False, height=False)
    return root


def deploy_play(root):
    # 时间块
    global time_text
    frame_time = tk.Frame(root)
    frame_time.pack(fill='x')
    frame_time_center = tk.Frame(frame_time)
    frame_time_center.pack(anchor='center')
    tk.Label(frame_time_center, text="当前时间", ).pack(side="left")
    time_text = tk.Label(frame_time_center, anchor="w")
    time_text.pack(side="left")
    time_text.config(width=20)

    def asyn_time():
        global time_start
        time_start = False
        if isinstance(T, threading.Thread):
            T.join()
        start_time_thread()

    time_btn = tk.Button(frame_time_center, text='同步时间',
                         command=asyn_time, padx=(10.0),)
    time_btn.pack(side="left")

    # 控制窗口
    frame_data = tk.Frame(root)
    frame_data.pack(fill='x')

    tk.Label(frame_data, text='延迟(分)').grid(
        row=0, column=0, padx=(10, 0), pady=(10, 0))
    data_delay = tk.Entry(frame_data)
    data_delay.grid(row=0, column=1, padx=(0, 0), pady=(10, 0))

    tk.Label(frame_data, text='窗口句柄：').grid(
        row=0, column=2, padx=(10, 0), pady=(10, 0))
    data_hwnd = tk.Entry(frame_data,)
    data_hwnd.grid(row=0, column=3, padx=(0, 0), pady=(10, 0))

    tk.Label(frame_data, text='任务：').grid(
        row=0, column=4, padx=(10, 0), pady=(10, 0))
    data_task_vars = []
    data_tasks_options = ['box', 'ad']
    default_checked = [tk.BooleanVar() for _ in data_tasks_options]
    for i, option in enumerate(data_tasks_options):
        data_task_vars.append(default_checked[i])
        data_task_vars[i].set(True)  # 设置默认选中
        tk.Checkbutton(
            frame_data, text=option, variable=data_task_vars[i]).grid(row=0, column=5+i, padx=(
                10, 0), pady=(10, 0), sticky="ew")

    frame_log = tk.Frame(root, padx=10, pady=10)
    frame_log.pack(fill=tk.BOTH, expand=True)

    # # 创建滚动条
    scrollbar = ttk.Scrollbar(frame_log, orient='vertical')
    scrollbar.pack(side=tk.RIGHT, fill=tk.Y)

    frame_left = tk.Canvas(
        frame_log, yscrollcommand=scrollbar.set, highlightthickness=0)
    frame_left.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)

    # # 设置滚动条的命令为Listbox的yview方法
    scrollbar.config(command=frame_left.yview)

    def on_button_click(index):
        for k in range(len(arr)):
            if arr[k]['index'] == index:
                arr[k]['switch'] = False
                if isinstance(arr[k]['threading'], threading.Thread):
                    arr[k]['threading'].join()
                start_thread(arr[k])
                break

    def on_button_click_pause(index):
        for k in range(len(arr)):
            if arr[k]['index'] == index:
                arr[k]['switch'] = False
                if isinstance(arr[k]['threading'], threading.Thread):
                    arr[k]['threading'].join()
                arr[k]['log_text'] = 'stop'
                arr[k]['log_label'].config(text='stop')
                break

    def on_button_click_del(index):
        for k in range(len(arr)):
            if arr[k]['index'] == index:
                arr[k]['switch'] = False
                if isinstance(arr[k]['threading'], threading.Thread):
                    arr[k]['threading'].join()
                del arr[k]
                update_create_log()
                break
        else:
            print("No matching item found")

    def update_create_log():
        global offset_y
        offset_y = 0
        frame_left.delete("all")
        for i in range(len(arr)):
            create_log(i)

    def create_log(k):
        global offset_y
        global arr
        global arr_index
        # 创建自定义的Frame来包含文本和按钮
        entry_frame = tk.Frame(frame_left, background='#f1f1f1')

        item_text = f"data_hwnd: {arr[k]['data_hwnd']}"

        # 在Frame中添加Label显示文本信息
        tk.Label(entry_frame, text=item_text,
                 background='#f1f1f1').pack(side=tk.LEFT)

        def on_change_data_delay(*args):
            if isinstance(arr[k]['threading'], threading.Thread):
                arr[k]['threading'].join()
            arr[k]['data_delay'] = data_delay_line_var.get().strip()
            print(arr)
        # 创建 StringVar 并将其与 Entry 绑定
        tk.Label(
            entry_frame, text='延迟(分)：', background='#f1f1f1', anchor='w').pack(side=tk.LEFT, fill=tk.BOTH)
        data_delay_line_var = tk.StringVar()
        data_delay_line_var.set(arr[k]['data_delay'])
        data_delay_line = tk.Entry(
            entry_frame, textvariable=data_delay_line_var)
        data_delay_line.pack(side="left")
        data_delay_line.config(width=4)
        data_delay_line_var.trace_add("write", on_change_data_delay)

        arr[k]['log_label'] = tk.Label(
            entry_frame, text=arr[k]['log_text'], background='#f1f1f1', width=60, anchor='w')
        arr[k]['log_label'].pack(side=tk.LEFT, fill=tk.BOTH)
        # 在Frame中添加Button并将其与点击事件关联

        button_del = ttk.Button(entry_frame, text="删除",
                                command=lambda: on_button_click_del(arr[k]['index']), width=4)
        button_del.pack(side=tk.RIGHT)
        button_pause = ttk.Button(entry_frame, text="重置",
                                  command=lambda: on_button_click_pause(arr[k]['index']), width=4)
        button_pause.pack(side=tk.RIGHT)
        button = ttk.Button(entry_frame, text="开始",
                            command=lambda: on_button_click(arr[k]['index']), width=4)
        button.pack(side=tk.RIGHT)

        entry_frame.update_idletasks()

        # 将entry_frame插入到Canvas中
        frame_left.create_window(
            (0, offset_y), window=entry_frame, anchor="nw", width=frame_left.winfo_width(), height=entry_frame.winfo_reqheight())
        # 更新偏移量
        offset_y = offset_y + entry_frame.winfo_reqheight()

        # 更新Canvas及滚动条
        frame_left.update_idletasks()
        frame_left.config(scrollregion=frame_left.bbox("all"))
        scrollbar.config(command=frame_left.yview)

    def submit():
        global arr_index
        data_tasks = []
        for i, option in enumerate(data_tasks_options):
            if data_task_vars[i].get():
                data_tasks.append(option)
        if not data_hwnd.get().strip():
            return
        obj = {
            'data_delay': int(data_delay.get().strip() or 0),
            'data_hwnd': int(data_hwnd.get().strip()),
            'data_tasks': data_tasks,
            'data_last_time': '',
            'log_text':  '',
            'log_label': '',
            'index': arr_index,
            'switch': True,
            'threading': None
        }
        data_delay.delete(0, 'end')
        data_hwnd.delete(0, 'end')
        arr.append(obj)
        arr_index += 1
        update_create_log()

    btn = tk.Button(frame_data, text='提交', command=submit)
    btn.grid(row=0, column=99, columnspan=1,
             rowspan=1, padx=(10, 0), pady=(10, 10))


def main():
    '''主函数'''
    # 初始化窗口
    root = create_windows()
    # 运行窗口
    deploy_play(root)
    start_time_thread()
    # 进入主循环
    root.mainloop()


if __name__ == '__main__':
    main()
